#include <stdio.h>
#include <stdlib.h>  
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


int main()
{
	pid_t id = fork();
	//child
	if(id == 0)
	{
		int cnt = 3;
		while(cnt--)
		{
			printf("child do something...PID:%d, PPID:%d\n", getpid(), getppid());
			sleep(3);
		}
		exit(0);
	}
	
	//parent
	while(1)
	{
		int status = 0;
		pid_t ret = waitpid(id, &status, WNOHANG);
		if(ret > 0)
		{
			printf("wait child success...\n");
			printf("exit code:%d\n", WEXITSTATUS(status));
			break;
		}
		else if(ret == 0)
		{
			printf("parent do other things...\n");
			sleep(1);
		}
		else
		{
			printf("waitpid error...\n");
			break;
		}
	}
	return 0;
}

/*int main()
{ 

	int ids[10] = {0};
	for(int i = 0; i < 10; ++i)
	{
		pid_t id  = fork();
		if(id == 0) //child
		{
			printf("child create success...:%d pid: %d, ppid: %d\n", i, getpid(), getppid());
			//sleep(1);
			exit(i);
		}
		//parent
		sleep(1);
		ids[i] = id;
	}

	int status = 0;
	for(int i = 0; i < 10; ++i)
	{
		pid_t ret = waitpid(ids[i], &status, 0);
		if(ret >= 0)
		{
			printf("wait success...\n");
			if(WIFEXITED(status))
			{
				//exit normal
				printf("exit code: %d\n", WEXITSTATUS(status));
				sleep(1);
			}
			else
			{
				//signal kill
				printf("exit signal: %d\n", status&0x7F);
				sleep(1);
			}
		}
	}

	return 0;
}*/



/*int main()
{
	pid_t id = fork();
	if(id == 0) //child
	{
		int count = 10;
		while(count)
		{
			printf("I am child..., pid: %d, ppid: %d\n", getpid(), getppid());
			sleep(1);
			count--;
		}
		exit(0);
	}
	
	//parent
	int status = 0;
	pid_t ret = waitpid(id, &status, 0);
	if(ret > 0)
	{
		printf("Wait success....\n");
		//wait success
		if(WIFEXITED(status))
		{
		       //exit normal
			printf("exit code: %d\n", WEXITSTATUS(status));
		}
		else
		{
			//signal kill
			printf("signal kill: %d\n", status&0x7F);	
		}
	}

	sleep(3);

	return 0;
}*/


/*int main()
{
	pid_t id = fork();
	if(id == 0) //child
	{
		int cnt = 10;
		while(cnt)
		{
			printf("I am child!. pid: %d, ppid: %d\n", getpid(), getppid());
			sleep(1);
			cnt--;
		}
		exit(0);
	}

	//parent
	int status = 0;
	pid_t ret = wait(&status);

	if(ret > 0)
	{
		printf("wait child success...\n");
		if(WIFEXITED(status)) //exit normal
		{
			printf("exit code: %d\n", WEXITSTATUS(status));
		}
	}

	sleep(3);
	return 0;
}*/
